﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GONES.IBLL;
using GONES.IDAL;
using GONES.Model;
using log4net;
using System.Reflection;
using GONES.Tools.Common;
using Newtonsoft.Json;

namespace GONES.BLL
{
    public class S_RoleManager : IS_RoleManager
    {
        public IS_RoleDao s_RoleDao;

        protected static readonly ILog Log =
            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public IS_LogDao S_LogDao;
        private readonly IUserInfo _userInfo;
        public S_LogManager S_LogManager;
        public string ErrMsg { get; set; }

        public S_RoleManager(IUserInfo userinfo)
        {
            _userInfo = userinfo;
        }

        public S_Role Get(string id)
        {
           return  s_RoleDao.Get(id);
        }

        public void Add(S_Role role)
        {
            if (IsError(role))
                return;
            role.CreateTime = System.DateTime.Now;
            s_RoleDao.Save(role);
            SaveLog("角色管理", "角色添加", "系统管理", role);
        }

        public void Edit(S_Role role)
        {
            if (IsError(role))
                return;
            role.ModifyTime = System.DateTime.Now;
            s_RoleDao.Update(role);
            SaveLog("角色管理", "角色修改", "系统管理", role);
        }

        public void Delete(string id)
        {
            S_Role role = s_RoleDao.Get(id);
            s_RoleDao.Delete(role);
            SaveLog( "角色管理", "角色删除","系统管理",role);
        }

        public IList<S_Role> List(IList<DataFilter> filters, int pageIndex, int pageSize, ref long recordCount)
        {
            string strFilter = DataOperate.GetHqlstrByExtFilter(filters, "e");

             recordCount = s_RoleDao.ExecHqlResultLong("SELECT COUNT(*) FROM S_Role e WHERE 1=1 " +
                                                  (string.IsNullOrEmpty(strFilter) ? string.Empty : " AND " + strFilter));

            return s_RoleDao.GetHqlList("SELECT e FROM S_Role e WHERE 1=1 " +
                                          (string.IsNullOrEmpty(strFilter)
                                               ? string.Empty
                                               : " AND " + strFilter) + " ORDER BY e.ID DESC", (pageIndex - 1) * pageSize,
                                          pageSize);
        }

        private void SaveLog(string module, string operate, string logtype, S_Role role)
        {
            S_LogManager = new S_LogManager(_userInfo);
            string detail = string.Format("{0}:角色名称是{1}", operate, role.RoleName);
            SaveLog(module, operate, logtype, detail);
            if (Log.IsInfoEnabled)
                Log.Info(string.Format("{0}：{1}", operate, JsonConvert.SerializeObject(role)));
        }

        protected bool IsError(S_Role role)
        {
            if (string.IsNullOrEmpty(role.RoleName))
            {
                ErrMsg = "角色名称不能为空!";
            }
            else if (s_RoleDao.GetList().Where(g => g.RoleName == role.RoleName).Count() > 0)
            {
                ErrMsg = "该角色名称已经存在!";
            }
            if (!string.IsNullOrEmpty(ErrMsg))
                return true;
            return false;
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="module">模块名称</param>
        /// <param name="operate">操作名称</param>
        /// <param name="logtype">日志类型（系统管理、基础资料等）</param>
        /// <param name="detail">详细日志</param>
        protected void SaveLog(string module, string operate, string logtype, string detail)
        {
            try
            {
                S_LogDao.Save(new S_Log
                {
                    ID = Rnd.Guid.ToString(),
                    Module = module,
                    Operate = operate,
                    Detail = detail,
                    LogType = logtype,
                    OpDate = DateTime.Now,
                    CreateUser = _userInfo.CLoginInfo.UserName,
                    CreateTime = DateTime.Now,
                    ModifyUser = _userInfo.CLoginInfo.UserName,
                    ModifyTime = DateTime.Now,
                    Ip = Tools.Common.Tools.GetIP()
                });
            }
            catch
            {
            }
        }
    }
}
